<template>
  <div class="supplier-management">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索供应商名称/编号/联系人"
        style="width: 360px"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="success" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加供应商
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="filteredSuppliers" 
      border 
      style="width: 100%"
      header-row-class-name="table-header"
      stripe
      highlight-current-row
    >
      <el-table-column prop="supplierId" label="供应商编号" width="160" sortable align="center" />
      <el-table-column prop="name" label="供应商名称" width="200" />
      <el-table-column prop="type" label="类型" width="140">
        <template #default="{ row }">
          <el-tag effect="plain" :type="typeTagType[row.type]">
            {{ row.type }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="contact" label="联系人" width="140" />
      <el-table-column prop="phone" label="联系电话" width="160" />
      <el-table-column prop="status" label="状态" width="120" align="center">
        <template #default="{ row }">
          <el-tag :type="statusTagType[row.status]" effect="light">
            {{ statusOptions.find(s => s.value === row.status)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="startDate" label="合作日期" width="140" sortable />
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="{ row }">
          <el-button size="small" type="primary" plain @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            plain
            @click="handleDelete(row.supplierId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑鲜花供应商信息' : '添加鲜花供应商'"
      width="680"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="供应商编号" prop="supplierId">
          <el-input 
            v-model="formData.supplierId" 
            :disabled="isEditMode"
            placeholder="FLW开头+3位数字"
          />
        </el-form-item>
        <el-form-item label="供应商名称" prop="name">
          <el-input v-model="formData.name" placeholder="例如：云南鲜花种植基地"/>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择类型">
            <el-option
              v-for="item in types"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="formData.contact" placeholder="请输入负责人姓名"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" />
        </el-form-item>
        <el-form-item label="联系地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入公司地址"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="合作日期" prop="startDate">
          <el-date-picker
            v-model="formData.startDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="success" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 供应商类型配置
const types = [
  '鲜花种植',
  '包装材料',
  '冷链物流',
  '进口贸易',
  '花艺工具',
  '肥料供应',
  '保鲜剂供应',
  '节日装饰'
]

// 类型标签样式映射
const typeTagType = {
  '鲜花种植': 'success',
  '包装材料': 'info',
  '冷链物流': 'warning',
  '进口贸易': 'danger',
  '花艺工具': '',
  '肥料供应': 'success',
  '保鲜剂供应': 'warning',
  '节日装饰': 'danger'
}

// 状态选项及样式
const statusOptions = [
  { value: 'active', label: '合作中' },
  { value: 'paused', label: '暂停合作' },
  { value: 'stopped', label: '终止合作' }
]

const statusTagType = {
  'active': 'success',
  'paused': 'warning',
  'stopped': 'danger'
}

// 初始供应商数据（10条鲜花相关）
const suppliers = ref([
  {
    supplierId: 'FLW001',
    name: '云南鲜花种植基地',
    type: '鲜花种植',
    contact: '张经理',
    phone: '13800138000',
    address: '云南省昆明市斗南花卉市场',
    status: 'active',
    startDate: '2023-01-01'
  },
  {
    supplierId: 'FLW002',
    name: '高端花艺包装公司',
    type: '包装材料',
    contact: '王总监',
    phone: '13800138001',
    address: '杭州市余杭区创意设计园',
    status: 'active',
    startDate: '2023-03-15'
  },
  {
    supplierId: 'FLW003',
    name: '冷链鲜花运输专家',
    type: '冷链物流',
    contact: '李主管',
    phone: '13800138002',
    address: '上海市浦东物流园区',
    status: 'active',
    startDate: '2022-11-01'
  },
  {
    supplierId: 'FLW004',
    name: '荷兰郁金香进口商',
    type: '进口贸易',
    contact: 'Hans',
    phone: '13800138003',
    address: '广州自贸区国际大厦',
    status: 'paused',
    startDate: '2023-05-20'
  },
  {
    supplierId: 'FLW005',
    name: '花艺工具制造厂',
    type: '花艺工具',
    contact: '陈工',
    phone: '13800138004',
    address: '江苏省南通市工业园',
    status: 'active',
    startDate: '2023-07-01'
  },
  {
    supplierId: 'FLW006',
    name: '有机肥料供应商',
    type: '肥料供应',
    contact: '赵厂长',
    phone: '13800138005',
    address: '山东省寿光农业基地',
    status: 'active',
    startDate: '2023-08-15'
  },
  {
    supplierId: 'FLW007',
    name: '鲜花保鲜剂公司',
    type: '保鲜剂供应',
    contact: '孙经理',
    phone: '13800138006',
    address: '广东省深圳市科技园',
    status: 'active',
    startDate: '2024-01-10'
  },
  {
    supplierId: 'FLW008',
    name: '圣诞花环供应商',
    type: '节日装饰',
    contact: '周小姐',
    phone: '13800138007',
    address: '义乌小商品城C区',
    status: 'stopped',
    startDate: '2023-09-01'
  },
  {
    supplierId: 'FLW009',
    name: '厄瓜多尔玫瑰进口',
    type: '进口贸易',
    contact: 'Emily',
    phone: '13800138008',
    address: '上海外高桥保税区',
    status: 'active',
    startDate: '2024-02-01'
  },
  {
    supplierId: 'FLW010',
    name: '永生花材料供应',
    type: '包装材料',
    contact: '王老师',
    phone: '13800138009',
    address: '北京市朝阳区艺术区',
    status: 'active',
    startDate: '2024-03-01'
  }
])

// 搜索功能
const searchText = ref('')
const filteredSuppliers = computed(() => {
  return suppliers.value.filter(supplier => {
    return Object.values(supplier).some(value => 
      String(value).toLowerCase().includes(searchText.value.toLowerCase())
  )})
})

// 对话框相关状态
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
const formData = reactive({
  supplierId: '',
  name: '',
  type: '',
  contact: '',
  phone: '',
  address: '',
  status: 'active',
  startDate: new Date().toISOString().split('T')[0]
})

// 表单验证规则
const formRules = {
  supplierId: [
    { required: true, message: '请输入供应商编号', trigger: 'blur' },
    { pattern: /^FLW\d{3}$/, message: '格式要求：FLW+3位数字', trigger: 'blur' }
  ],
  name: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择供应商类型', trigger: 'change' }],
  contact: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效手机号码', trigger: 'blur' }
  ],
  address: [{ required: true, message: '请输入联系地址', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择合作日期', trigger: 'change' }],
  status: [{ required: true, message: '请选择合作状态', trigger: 'change' }]
}

// 操作函数
const handleAdd = () => {
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEditMode.value = true
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

const handleDelete = (supplierId) => {
  ElMessageBox.confirm('确定要删除该鲜花供应商吗？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    suppliers.value = suppliers.value.filter(u => u.supplierId !== supplierId)
    ElMessage.success('删除成功')
  })
}

const submitForm = async () => {
  await formRef.value.validate()
  if (isEditMode.value) {
    const index = suppliers.value.findIndex(u => u.supplierId === formData.supplierId)
    suppliers.value.splice(index, 1, { ...formData })
  } else {
    if (suppliers.value.some(u => u.supplierId === formData.supplierId)) {
      return ElMessage.warning('供应商编号已存在')
    }
    suppliers.value.push({ ...formData })
  }
  dialogVisible.value = false
  ElMessage.success(isEditMode.value ? '修改成功' : '添加成功')
}

const resetForm = () => {
  formData.supplierId = ''
  formData.name = ''
  formData.type = ''
  formData.contact = ''
  formData.phone = ''
  formData.address = ''
  formData.status = 'active'
  formData.startDate = new Date().toISOString().split('T')[0]
}
</script>

<style scoped lang="scss">
.supplier-management {
  padding: 24px;
  background: #f8fafc;
  min-height: 100vh;

  .operation-bar {
    padding: 16px 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(28, 36, 56, 0.08);
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 16px;
  }

  :deep(.table-header) th {
    background-color: #f8fafc !important;
    color: #64748b;
    font-weight: 600;
    height: 56px;
  }

  .el-table {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(28, 36, 56, 0.08);
    
    .el-tag {
      font-size: 13px;
      padding: 0 8px;
      height: 26px;
      line-height: 24px;
    }
  }
}

.el-dialog {
  border-radius: 12px;
  
  .el-dialog__header {
    border-bottom: 1px solid #e2e8f0;
    margin: 0 24px;
    padding: 24px 0 16px;
  }
  
  .el-dialog__body {
    padding: 24px 32px;
  }
  
  .el-dialog__footer {
    border-top: 1px solid #e2e8f0;
    padding: 16px 24px;
  }
}

.el-form-item {
  margin-bottom: 20px;
}
</style>